/**
 * Copyright FunASR (https://github.com/alibaba-damo-academy/FunASR). All Rights
 * Reserved. MIT License  (https://opensource.org/licenses/MIT)
 */
/* 2022-2023 by zhaoming,mali aihealthx.com */
var wsconnecter // 连接实例化
var isRec // 是否开始录音
var rec // 录音实例化
var sampleBuf = new Int16Array()
// let URI = "wss://www.funasr.com:10096/" 
let URI = "wss://loghvarvest-hamis-test.ssc-hn.com:30999/funasr" 

var isfilemode = false // if it is in file mode
var file_ext = ''
var file_sample_rate = 16000 //for wav file sample rate
var file_data_array // array to save file data

function recProcessMethod(
  buffer,
  powerLevel,
  bufferDuration,
  bufferSampleRate,
  newBufferIdx,
  asyncEnd
) {
  if (isRec === true) {
    var data_48k = buffer[buffer.length - 1]
    var array_48k = new Array(data_48k)
    var data_16k = Recorder.SampleData(array_48k, bufferSampleRate, 16000).data
    sampleBuf = Int16Array.from([...sampleBuf, ...data_16k])
    var chunk_size = 960 // for asr chunk_size [5, 10, 5]
    while (sampleBuf.length >= chunk_size) {
      const sendBuf = sampleBuf.slice(0, chunk_size)
      sampleBuf = sampleBuf.slice(chunk_size, sampleBuf.length)
      wsconnecter.wsSend(sendBuf)
    }
  }
}

// 初始化并建立连接
function initWebSocketConnectMethod(params) {
  const { uri, recorder, ...others } = params || {}
  wsconnecter = new WebSocketConnectMethod({
    ...others,
    msgHandle: (jsonMsg) => {
      const data = JSON.parse(jsonMsg.data)
      if (data.is_final == true) {
        wsconnecter.wsStop()
      }
      others?.msgHandle?.(data)
    }
  })
  rec = Recorder({
    type: 'pcm',
    bitRate: 16,
    sampleRate: 16000,
    ...recorder,
    onProcess: (...params) => {
      recorder?.onProcess?.(...params)
      recProcessMethod(...params)
    },
  })
  
  uri && (URI = uri)
}

function startRecordMethod(cb) {
  //启动连接
	const ret=wsconnecter.wsStart(URI);
  if(ret) {
    rec.open(function () {
      // 成功回调
      isRec = true
      rec.start()
      cb && cb(1)
    }, function() {
      // 失败回调
      cb && cb(0)
      // 不能用同步关闭，不然会报连接未建立就关闭的错误
      setTimeout(() => {
        wsconnecter.wsStop()
      }, 500)
    })
  }
}

function pauseRecordMethod(cb) {
  rec.pause()
  cb && cb()
}

function resumeRecordMethod(cb) {
  rec.resume()
  cb && cb()
}

function stopRecordMethod(cb) {
  var chunk_size = new Array(5, 10, 5)
  var request = {
    chunk_size: chunk_size,
    wav_name: 'h5',
    is_speaking: false,
    chunk_interval: 10,
    mode: getAsrMode()
  }
  if (sampleBuf.length > 0) {
    wsconnecter.wsSend(sampleBuf)
    sampleBuf = new Int16Array()
  }
  wsconnecter.wsSend(JSON.stringify(request))

  isRec = false
  wsconnecter.wsStop()

  rec.stop(
    function (blob, duration) {
      var audioBlob = Recorder.pcm2wav(
        (data = { sampleRate: 16000, bitRate: 16, blob: blob }),
        function (theblob, duration) {
          const src = (window.URL || webkitURL).createObjectURL(theblob);
          cb?.(src)
          // var audio_record = document.getElementById('audio_record')
          // audio_record.src = (window.URL || webkitURL).createObjectURL(theblob)
          // audio_record.controls = true
          //audio_record.play();
        },
        function (msg) {
          console.log(msg)
        }
      )
    },
    function (errMsg) {
      console.log('errMsg: ' + errMsg)
    }
  )
}

// 逆文本标准化
function getUseITN() {
  return false
}

// 存在 2pass、online、offline模式
function getAsrMode() {
  return '2pass'
}

// 设置热词
function getHotwords() {
  const jsonresult = ['医生', '患者', '生病', '医药']
  return JSON.stringify(jsonresult)
}
